package com.atguigu.yygh.hosp.receiver;

import com.atguigu.yygh.common.service.MqConst;
import com.atguigu.yygh.common.service.RabbitService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.message.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        //1、获取参数，下单成功更新预约数
        String hoscode = orderMqVo.getHoscode();
        String hosScheduleId = orderMqVo.getHosScheduleId();
        //2、查询排班记录
        Schedule schedule = scheduleService.getScheduleByIds(hoscode,hosScheduleId);
        //3、更新号源
        Integer availableNumber = orderMqVo.getAvailableNumber();//更新剩余预约数
        Integer reservedNumber = orderMqVo.getReservedNumber(); //更新可预约数
        //3.5判断是创建订单还是取消预约
        if ( availableNumber == null){
            //取消预约
            availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);//号源回退
//            reservedNumber = schedule.getReservedNumber();
        }else { //剩余预约数不为空
            schedule.setReservedNumber(reservedNumber);
            schedule.setAvailableNumber(availableNumber);
        }
        schedule.setUpdateTime(new Date());
        scheduleService.update(schedule);
        //4、发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_DIRECT_MSM,
                    MqConst.ROUTING_MSM_ITEM,
                    msmVo
            );
        }
    }
}
